/*
 * 主播认证
 * page主播认证
 */
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:qgchat/common/action/compress_photo/index.dart';
import 'package:qgchat/common/global/global.dart';
import 'package:qgchat/http/io.dart';
import 'package:qgchat/http/models/tagModel.dart';
import 'package:qgchat/page/my/sign/index.dart';
import 'package:qgchat/page/my/tag/index.dart';
import 'package:qgchat/widgets/line.dart';
import 'package:qgchat/widgets/iosBottomSheet.dart';
import 'package:city_pickers/city_pickers.dart';
import 'package:image_picker/image_picker.dart';

class AnchorAuth extends StatefulWidget {
  AnchorAuth({Key key}) : super(key: key);

  @override
  AanchorAuthState createState() => AanchorAuthState();
}

class AanchorAuthState extends State<AnchorAuth> {
  // 轮播图List
  List<Image> imgList = [];
  // 提交的轮播图
  List tisimage = [];
  // 身高
  String height = '';
  // 体重
  String weight = '';
  // 星座
  String constellation = "";
  // 所在城市
  String city = "";
  // 形象标签
  List<TagModel> label = [];
  // 已选择形象标签
  List selectlabel = [];
  // 个性签名
  String sign = "";

  // 12星座数组
  List<String> constellatory = [
    "白羊座",
    "金牛座",
    "双子座",
    "巨蟹座",
    "狮子座",
    "处女座",
    "天秤座",
    "天蝎座",
    "射手座",
    "摩羯座",
    "水瓶座",
    "双鱼座",
  ];

  // 渲染范围内的递增数组
  List<String> increaseListRender(min, max) {
    List<String> arr = [];
    for (var i = 0; i <= (max - min); i++) {
      String item = (min + i).toString();
      arr.add(item);
    }
    return arr;
  }

  // 提交或修改
  void _modification() {
    label.forEach((f){
      selectlabel.add(f.id);
    });
    Io.post('auth',data:{
      'anchor_height':'$height',
      'anchor_weight':'$weight',
      'anchor_star':'$constellation',
      'anchor_city':'$city',
      'anchor_tag':selectlabel,
      'anchor_img':tisimage,
      'anchor_sign':'$sign'
    }).then((res){
     if(res['status'] == 1){
       showToast(res['msg']);
     }else{
       showToast(res['msg']);
     }
    });
  }

  // 点击当前轮播图
  void _swiperItemClick(int index) {
    print('当前第${index + 1}个轮播图被点击');
  }

  void chockimage(img) {
    Io.updateFile('vedio/upload', img, size: '51200000').then((res) {
      print('-----');
      print(res.data);
      print('-----');
      if (res.data['status'] == 1) {
        imgList.add(Image.network(
          res.data['data'],
          fit: BoxFit.cover,
        ));
        tisimage.add(res.data['data']);
        setState(() {
          imgList = imgList;
          tisimage = tisimage;
        });
      } else {
        showToast(res.data['msg']);
      }
    });
  }

  // 相机按钮被点击
  void _cameraClick() {
    if (imgList.length < 9) {
      showCupertinoModalPopup(
        context: context,
        builder: (BuildContext context) {
          return CupertinoActionSheet(
            title: Text("选择图片"),
            message: Text("选择以下选项获取图片"),
            cancelButton: CupertinoActionSheetAction(
              onPressed: () => Navigator.pop(context),
              child: Text("取消"),
            ),
            actions: <Widget>[
              CupertinoActionSheetAction(
                onPressed: () async {
                  var image =await ImagePicker.pickImage(source: ImageSource.camera);
                  CompressPhoto.compressPhoto(image, (file) {
                    chockimage(file);
                  });
                  Navigator.pop(context);
                },
                child: Text("相机"),
              ),
              CupertinoActionSheetAction(
                onPressed: () async {
                  var image =await ImagePicker.pickImage(source: ImageSource.gallery);
                  CompressPhoto.compressPhoto(image, (file) {
                    chockimage(file);
                  });
                  Navigator.pop(context);
                },
                child: Text("系统相册"),
              ),
            ],
          );
        },
      );
    } else {
      showToast('最多添加9张图片');
    }
  }

// -----------------------------------------------------------------------------

  /// appbar
  Widget appBar() {
    return PreferredSize(
      preferredSize: Size.fromHeight(px(88)),
      child: AppBar(
        leading: IconButton(
          icon: Icon(
            Icons.arrow_back_ios,
            color: Colors.black,
            size: px(36),
          ),
          onPressed: () => Navigator.of(context).pop(),
        ),
        centerTitle: true,
        elevation: 0,
        title: Text(
          '主播认证',
          style: TextStyle(
            fontSize: px(34),
            color: col('000000'),
            fontWeight: FontWeight.bold,
          ),
        ),
        actions: <Widget>[
          Center(
            child: Container(
              width: px(110),
              height: px(100),
              child: FlatButton(
                padding: EdgeInsets.all(px(0)),
                onPressed: _modification,
                child: Text(
                  '提交',
                  style: TextStyle(
                    fontSize: px(34),
                  ),
                ),
              ),
            ),
          )
        ],
      ),
    );
  }

  /// 轮播
  Widget swiperWidget() {
    // 轮播组件
    Widget swiperWidget = Swiper(
      onTap: (int index) {
        _swiperItemClick(index);
      },
      itemCount: imgList.length,
      itemBuilder: (BuildContext context, int index) {
        return imgList[index];
      },
      pagination: SwiperCustomPagination(
          builder: (BuildContext context, SwiperPluginConfig config) {
        return Align(
          alignment: Alignment.bottomCenter,
          child: Container(
            width: px(92),
            height: px(54),
            margin: EdgeInsets.only(bottom: px(25)),
            alignment: Alignment.center,
            decoration: BoxDecoration(
                color: Colors.black.withOpacity(0.32),
                borderRadius: BorderRadius.circular(px(27))),
            child: Text(
              '${config.activeIndex + 1}/${imgList.length}',
              style: TextStyle(fontSize: px(26), color: col('ffffff')),
            ),
          ),
        );
      }),
    );

    // 上传图组件
    Widget upload = Positioned(
      top: px(0),
      right: px(0),
      child: Container(
        width: px(100),
        height: px(100),
        child: FlatButton(
          onPressed: _cameraClick,
          padding: EdgeInsets.zero,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.all(
              Radius.circular(
                px(50),
              ),
            ),
          ),
          child: Container(
            width: px(44),
            height: px(40),
            child: Image.asset('assets/images/icon/camera.png'),
          ),
        ),
      ),
    );

    // 提示语
    Widget tips = Positioned(
      bottom: px(25),
      child: Text(
        "最多能上传9张图片",
        style: TextStyle(
          color: col("909399"),
          fontSize: px(26),
        ),
      ),
    );

    List<Widget> listWidget = [];
    if (imgList.isNotEmpty) {
      if (imgList != null) {
        listWidget.add(swiperWidget);
      }
    }
    listWidget.add(upload);
    if (imgList.isEmpty) {
      listWidget.add(tips);
    }

    return Container(
      height: px(750),
      color: col("f5f7fa"),
      child: Stack(
        alignment: Alignment.center,
        children: listWidget,
      ),
    );
  }

  /// 私人信��标题
  Widget privateInfo() {
    return Container(
      margin: EdgeInsets.only(top: px(50)),
      padding: EdgeInsets.symmetric(horizontal: px(30)),
      child: Text(
        '私人信息',
        style: TextStyle(
          fontSize: px(44),
          color: col('303133'),
          height: 1,
          fontWeight: FontWeight.bold,
        ),
      ),
    );
  }

  /// 私人信息子项
  Widget infoItem(
    String k,
    String v,
    List<String> list,
    Function choiceAction,
  ) {
    return Container(
      width: w100(context),
      height: px(180),
      padding: EdgeInsets.symmetric(horizontal: px(42)),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Container(
            margin: EdgeInsets.only(top: px(50)),
            child: Text(
              k,
              style: TextStyle(
                fontSize: px(26),
                color: col('909399'),
                height: 1,
              ),
            ),
          ),
          Container(
            child: FlatButton(
              onPressed: () {
                showModalBottomSheet(
                  context: context,
                  backgroundColor: Colors.white,
                  isScrollControlled: true,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(px(28)),
                      topRight: Radius.circular(px(28)),
                    ),
                  ),
                  builder: (BuildContext context) {
                    return IosBottomSheet(list, choiceAction);
                  },
                );
              },
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(sp(41)),
              ),
              padding: EdgeInsets.all(0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  Container(
                    child: Text(
                      v,
                      style: TextStyle(
                        fontSize: px(34),
                        color: col('303133'),
                        height: 1,
                      ),
                    ),
                  ),
                  Container(
                    child: Image.asset(
                      "assets/images/icon/down.png",
                      width: px(22),
                      height: px(14),
                    ),
                  )
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 私人信息子项
  Widget infoItem2(
    String k,
    String v,
    Function choiceAction,
  ) {
    return Container(
      width: w100(context),
      height: px(180),
      padding: EdgeInsets.symmetric(horizontal: px(42)),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Container(
            margin: EdgeInsets.only(top: px(50)),
            child: Text(
              k,
              style: TextStyle(
                fontSize: px(26),
                color: col('909399'),
                height: 1,
              ),
            ),
          ),
          Container(
            child: FlatButton(
              onPressed: choiceAction,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(sp(41)),
              ),
              padding: EdgeInsets.zero,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  Container(
                    child: Text(
                      v,
                      style: TextStyle(
                        fontSize: px(34),
                        color: col('303133'),
                        height: 1,
                      ),
                    ),
                  ),
                  Image.asset(
                    "assets/images/icon/down.png",
                    width: px(22),
                    height: px(14),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 形象标签
  Widget tagsItem() {
    List<Widget> tags() {
      return label.map((item) {
        return _tag(item.tagName);
      }).toList()
        ..add(

            /// 右箭头
            Container(
          height: px(26),
          margin: EdgeInsets.only(left: px(10)),
          child: Image.asset('assets/images/icon/right.png'),
        ));
    }

    return Container(
      width: w100(context),
      height: px(124),
      padding: EdgeInsets.symmetric(horizontal: px(42)),
      child: FlatButton(
//        onPressed: () => goPage(context, "/tag"),
        onPressed: () {
          Navigator.of(context)
              .push(MaterialPageRoute(
            builder: (context) => Tag(
              importantTags: label,
            ),
          ))
              .then((data) {
            setState(() {
              if (data != null) {
                label = data;
              }
            });
          });
        },
        padding: EdgeInsets.zero,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Container(
              child: Text(
                '形象标签',
                style: TextStyle(
                  fontSize: px(26),
                  color: col('909399'),
                  height: 1.2,
                ),
              ),
            ),
            Container(
              child: Row(
                children: tags(),
              ),
            )
          ],
        ),
      ),
    );
  }

  /// 标签
  Widget _tag(String tagText) {
    return Container(
      height: px(54),
      alignment: Alignment.center,
      padding: EdgeInsets.symmetric(horizontal: px(21)),
      margin: EdgeInsets.only(right: px(15)),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(px(27)),
        color: col('6f53ff'),
      ),
      child: Text(
        tagText,
        style: TextStyle(fontSize: px(26), color: col('fefefe'), height: 1.2),
      ),
    );
  }

  /// 个性签名
  Widget signature(String signatureText) {
    return Container(
      width: w100(context),
      height: px(124),
      padding: EdgeInsets.symmetric(horizontal: px(42)),
      child: FlatButton(
//        onPressed: () => goPage(context, "/sign"),
        onPressed: () {
          Navigator.of(context)
              .push(MaterialPageRoute(
            builder: (context) => Sign(
              signature: sign,
            ),
          ))
              .then((data) {
            setState(() {
              if (data != null) {
                sign = data;
              }
            });
          });
        },
        padding: EdgeInsets.zero,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Container(
              child: Text(
                '个性签名',
                style: TextStyle(
                    fontSize: px(26), color: col('909399'), height: 1.2),
              ),
            ),
            Container(
              child: Row(
                children: <Widget>[
                  Container(
                    width: px(434),
                    child: Text(
                      signatureText,
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(fontSize: px(26), color: col('909090')),
                    ),
                  ),

                  /// 右箭头
                  Container(
                    height: px(26),
                    margin: EdgeInsets.only(left: px(10)),
                    child: Image.asset('assets/images/icon/right.png'),
                  )
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: appBar(),
      body: Container(
        child: SingleChildScrollView(
          physics: BouncingScrollPhysics(),
          child: SafeArea(
            bottom: true,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                swiperWidget(),
                privateInfo(),
                infoItem(
                  '身高',
                  height,
                  increaseListRender(100, 230),
                  (item, index) {
                    setState(() {
                      height = item;
                    });
                  },
                ),
                Line(margin: EdgeInsets.symmetric(horizontal: px(30))),
                infoItem(
                  '体重',
                  weight,
                  increaseListRender(20, 100),
                  (item, index) {
                    setState(() {
                      weight = item;
                    });
                  },
                ),
                Line(margin: EdgeInsets.symmetric(horizontal: px(30))),
                infoItem(
                  '星座',
                  constellation,
                  constellatory,
                  (item, index) {
                    setState(() {
                      constellation = item;
                    });
                  },
                ),
                Line(margin: EdgeInsets.symmetric(horizontal: px(30))),
                infoItem2(
                  '所在城市',
                  city,
                  () async {
                    Result result = await CityPickers.showCityPicker(
                      context: context,
                      height: px(500),
                    );
                    setState(() {
                      if (result?.provinceName != null) {
                        city =
                            "${result?.provinceName}${result?.cityName}${result?.areaName}";
                      }
                    });
                  },
                ),
                Line(margin: EdgeInsets.symmetric(horizontal: px(30))),
                tagsItem(),
                Line(margin: EdgeInsets.symmetric(horizontal: px(30))),
                signature(sign),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
